package com.css.fxfzypg.modules.baseData.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.common.utils.CheckObjFields;
import com.css.fxfzypg.common.utils.UpdateUtil;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.baseData.queryParams.GdpQueryParams;
import com.css.fxfzypg.modules.baseData.repository.GdpRepositpory;
import com.css.fxfzypg.modules.baseData.entity.GdpEntity;
import com.css.fxfzypg.modules.baseData.service.GdpService;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author y1fan
 * @create 2022-08-11 16:53
 */
@Service
public class GdpServiceImpl implements GdpService {

    @Resource
    private GdpRepositpory gdpRepositpory;

    @Resource
    private SysAreaService sysAreaService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SUserService sUserService;

    /**
     * GDP数据保存
     *
     * @param gdpEntity GDP数据实体类
     * @return 保存到数据库的数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveGdp(GdpEntity gdpEntity) {
        if (PlatformObjectUtils.isEmpty(gdpEntity.getGdp())) {
            return 0;
        }
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        gdpEntity.setGdpId(UUIDGenerator.getUUID());
        gdpEntity.setCreateUser(PlatformSessionUtils.getUserId());
        gdpEntity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        gdpEntity.setIsDelete(YNEnum.N.toString());
        String divisionIds = null;
        try {
            //判断省市县的名称是否符合规范
            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(gdpEntity.getProvince(), "utf-8"),
                    URLEncoder.encode(gdpEntity.getCity(), "utf-8"),
                    URLEncoder.encode(gdpEntity.getPrefecture(), "utf-8"));
        } catch (Exception e) {
            return 0;
        }
        String[] split = divisionIds.split("_");
        gdpEntity.setProvinceId(split[0]);
        if (split.length == 2) {
            gdpEntity.setCityId(split[0]);
            gdpEntity.setPrefectureId(split[1]);
        } else {
            gdpEntity.setCityId(split[1]);
            gdpEntity.setPrefectureId(split[2]);
        }
        gdpEntity.setProvinceCode(areaIdCodeMap.get(gdpEntity.getProvinceId()));
        gdpEntity.setCityCode(areaIdCodeMap.get(gdpEntity.getCityId()));
        gdpEntity.setPrefectureCode(areaIdCodeMap.get(gdpEntity.getPrefectureId()));
        return gdpRepositpory.saveGdp(gdpEntity);
    }

    /**
     * 根据gdpId查询到单条数据
     *
     * @param id 实体id:gdpId
     * @return 单条实体类数据
     */
    @Override
    public Object getGdpById(String id) {
        return gdpRepositpory.getGdpById(id);
    }

    /**
     * 修改
     *
     * @param gdpEntity GDP数据实体类
     * @return 修改到数据库的数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateGdp(GdpEntity gdpEntity) {
        if (PlatformObjectUtils.isEmpty(gdpEntity.getGdp())) {
            return 0;
        }
        if (PlatformObjectUtils.isEmpty(gdpEntity.getPeoAvgGdp())) {
            gdpEntity.setPeoAvgGdp(BigDecimal.ZERO);
        }
        GdpEntity gdpById = gdpRepositpory.getGdpById(gdpEntity.getGdpId());
        UpdateUtil.copyNullProperties(gdpById, gdpEntity);
        gdpEntity.setUpdateUser(PlatformSessionUtils.getUserId());
        gdpEntity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        return gdpRepositpory.updateGdp(gdpEntity);
    }

    /**
     * 根据条件分页查询
     *
     * @param queryParams 分页查询的条件
     * @param curPage     第几页数据
     * @param pageSize    一页多少条数据
     * @return JSONObject
     * jsonObject.put("rows", gdpEntities); 数据
     * jsonObject.put("total", total); 数据总条数
     */
    @Override
    public JSONObject getAllGdpByParams(GdpQueryParams queryParams, int curPage, int pageSize) {
        JSONObject jsonObject = this.gdpRepositpory.getAllPeoByParams(queryParams, curPage, pageSize);
        return jsonObject;
    }

    /**
     * 逻辑删除
     *
     * @param id 实体id:gdpId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteGdp(String id) {
        String userId = PlatformSessionUtils.getUserId();
        Timestamp currentTimestamp = PlatformDateUtils.getCurrentTimestamp();
        gdpRepositpory.deleteGdpByIds(id, userId, currentTimestamp);
    }

    /**
     * 导入
     *
     * @param file 文件
     * @return 导入的信息
     * @throws IOException IO流异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse importExcel(MultipartFile file) throws IOException {
        Map<String, String> areaIdCodeMap = (Map<String, String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
        List<GdpEntity> gdpEntities = FileUtil.importExcel(file, 0, 1, GdpEntity.class);
        //存储错误的信息
        StringBuilder erorrMesegger = new StringBuilder();
        //存储insert数据
        List<GdpEntity> saveList = new ArrayList<>();
        //存储update数据
        List<GdpEntity> updateList = new ArrayList<>();
        int count = 0;
        for (GdpEntity gdpEntity : gdpEntities) {
            if (CheckObjFields.isAllFieldNull(gdpEntity)) {
                count++;
                continue;
            }
            //判断必填项是否存在空值
            if (PlatformObjectUtils.isEmpty(gdpEntity.getProvince()) || PlatformObjectUtils.isEmpty(gdpEntity.getCity()) || PlatformObjectUtils.isEmpty(gdpEntity.getPrefecture()) || PlatformObjectUtils.isEmpty(gdpEntity.getGdp())) {
                erorrMesegger.append("第" + (gdpEntities.indexOf(gdpEntity) + 2) + "行数据，必填项存在空值！！<br/>");
                continue;
            }
            String divisionIds = null;
            try {
                //判断省市县的名称是否符合规范
                divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(gdpEntity.getProvince(), "utf-8"),
                        URLEncoder.encode(gdpEntity.getCity(), "utf-8"),
                        URLEncoder.encode(gdpEntity.getPrefecture(), "utf-8"));
            } catch (Exception e) {
            }
            if (PlatformObjectUtils.isEmpty(divisionIds)) {
                erorrMesegger.append("第" + (gdpEntities.indexOf(gdpEntity) + 2) + "行数据，省市县的名称不规范！！<br/>");
                continue;
            }
            //判断导入的数据，数据库里是否存在
            GdpEntity gdpByDivision = gdpRepositpory.getGdpByDivision(gdpEntity.getProvince(), gdpEntity.getCity(), gdpEntity.getPrefecture());
            if (PlatformObjectUtils.isEmpty(gdpByDivision)) {
                //不存在则insert
                saveList.add(gdpEntity);
            } else {
                //存在则update
                gdpByDivision.setGdp(gdpEntity.getGdp());
                if (PlatformObjectUtils.isNotEmpty(gdpEntity.getPeoAvgGdp())) {
                    gdpByDivision.setPeoAvgGdp(gdpEntity.getPeoAvgGdp());
                }
                gdpByDivision.setUpdateUser(PlatformSessionUtils.getUserId());
                gdpByDivision.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                updateList.add(gdpByDivision);
            }
        }
        if (erorrMesegger.length() != 0) {
            return RestResponse.fail("导入失败:".concat(String.valueOf(erorrMesegger)));
        }
        //存储保存或修改数据库数据的条数
        int saveNum = 0;
        if (PlatformObjectUtils.isNotEmpty(saveList)) {
            for (GdpEntity gdpEntity : saveList) {
                gdpEntity.setProvinceCode(areaIdCodeMap.get(gdpEntity.getProvinceId()));
                gdpEntity.setCityCode(areaIdCodeMap.get(gdpEntity.getCityId()));
                gdpEntity.setPrefectureCode(areaIdCodeMap.get(gdpEntity.getPrefectureId()));
                int i = this.saveGdp(gdpEntity);
                saveNum = saveNum + i;
            }
        }
        if (PlatformObjectUtils.isNotEmpty(updateList)) {
            int[] ints = gdpRepositpory.importExcel(updateList);
            saveNum = saveNum + ints.length;
        }
        return ResponseCreator.createSuccessResponse(null, "导入成功" + saveNum + "条，一共" + (gdpEntities.size() - count) +
                "条!");
    }

    /**
     * 导出
     *
     * @param response 响应
     * @throws IOException IO流异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<GdpEntity> list = gdpRepositpory.exportExcel();
        FileUtil.exportExcel(list, "GDP数据表", "sheet", GdpEntity.class, "GDPExcel", response);
    }

    @Override
    public String getLanderRoles() {
        //List<Map<String,Object>> list=new ArrayList<>();
        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        //String user = sUserService.getSUser(userId);
        //SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        //String province = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());

        for (Map roleMap : roleMaps) {
            if ("ypg_coun_gl_role".equals(roleMap.get("roleCode"))) {
                /*Map<String,Object> m=new HashMap<>();
                m.put("role","国家管理员");
                list.add(m);*/
                str.append("国家管理员" + ",");
            } else if ("ypg_coun_yw_role".equals(roleMap.get("roleCode"))) {
                /*Map<String,Object> m=new HashMap<>();
                m.put("role","国家业务员");
                list.add(m);*/
                str.append("国家业务员" + ",");
            } else if ("ypg_pri_gl_role".equals(roleMap.get("roleCode"))) {
                /*Map<String,Object> m=new HashMap<>();
                m.put("role","省管理员");
                m.put("province",province);
                list.add(m);*/
                str.append("省管理员" + ",");
            } else if ("ypg_pri_yw_role".equals(roleMap.get("roleCode"))) {
                /*Map<String,Object> m=new HashMap<>();
                m.put("role","省业务员");
                m.put("province",province);
                list.add(m);*/
                str.append("省业务员" + ",");
            }
        }
        String roles = str.toString().substring(0, str.length() - 1);
        return roles;
    }

    @Override
    public String getLanderProvince() {
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        return sUser.getProvinceId();
    }

    @Override
    public Integer countByCounty(String province, String city, String county) {
        return gdpRepositpory.countByCounty(province, city, county);
    }

    @Override
    public Integer countByCity(String province, String city) {
        return gdpRepositpory.countByCity(province, city);
    }

    @Override
    public Integer countByProvince(String name) {
        return gdpRepositpory.countByProvince(name);
    }

    @Override
    public Integer countByProvinceAndYear(String provinceName, String taskYear) {
        return gdpRepositpory.countByProvinceAndYear(provinceName, taskYear);
    }
}
